package com.chen.Sign.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.Sign.common.Result;
import com.chen.Sign.mapper.Blog_commentMapper;
import com.chen.Sign.pojo.Blog_comment;
import com.chen.Sign.service.impl.Blog_commentServiceImpl;
import com.chen.Sign.service.impl.UserServiceImpl;
import com.chen.Sign.utils.BeanCopyUtils;
import com.chen.Sign.utils.JWTUtils;
import com.chen.Sign.vo.Blog_commentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;



@Slf4j
@RestController
@SuppressWarnings({"all"})
@RequestMapping("/comment")
public class Blog_commentController {

    @Autowired
    private Blog_commentServiceImpl blog_commentService;

    @Autowired
    private Blog_commentMapper blog_commentMapper;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 查看评论
     * @param articleId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/commentList")
    public Result commentList(Integer blogId, Integer pageNum, Integer pageSize) {

        // 查询对应文章的根评论
        LambdaQueryWrapper<Blog_comment> queryWrapper = new LambdaQueryWrapper<>();
        // 对articleld进行判断

        queryWrapper.eq(Blog_comment::getBlogId, blogId);
        // 根评论 rootId为-1
        queryWrapper.eq(Blog_comment::getRootId, -1);
        // 分页查询
        Page<Blog_comment> page = new Page<>(pageNum, pageSize);
        blog_commentMapper.selectPage(page, queryWrapper);

        List<Blog_commentVo> commentVoList = toCommentVoList(page.getRecords());

        // 查询所有根评论对应的子评论集合，并且赋值给对应的属性
        for (Blog_commentVo commentVo : commentVoList) {
            // 查询对应的子评论
           List<Blog_commentVo> children =  getChildren(commentVo.getId());
            // 赋值
            commentVo.setChildren(children);
        }

        return new Result(1, "获取评论成功", commentVoList);
    }

    /**
     * 根据根评论的id查询所对应的子评论的集合
     * @param id
     * @return
     */
    private List<Blog_commentVo> getChildren(Long id) {
        LambdaQueryWrapper<Blog_comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog_comment::getRootId,id).orderByAsc(Blog_comment::getCreateTime);

        List<Blog_comment> comments = blog_commentMapper.selectList(queryWrapper);

        List<Blog_commentVo> commentVoList = toCommentVoList(comments);
        return commentVoList;
    }

    private List<Blog_commentVo> toCommentVoList(List<Blog_comment> list) {
        List<Blog_commentVo> commentVoList = BeanCopyUtils.copyBeanList(list, Blog_commentVo.class);
        // 遍历vo集合
        for (Blog_commentVo blog_commentVo : commentVoList) {
            // 通过createBy查询用户的昵称并赋值
            String nickname = userService.getById(blog_commentVo.getCreateBy()).getNickname();
            blog_commentVo.setUsername(nickname);
            // 通过toCommentUserId查询用户的昵称并赋值
            if (blog_commentVo.getToCommentUserId()!=-1) {
                String toCommentUserName = userService.getById(blog_commentVo.getToCommentUserId()).getNickname();
                blog_commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVoList;
    }

    /**
     * 添加评论
     * @param blog_comment
     * "articleId"
     * "rootId"
     * "toCommentId"
     * "toCommentUserId"
     * "content"
     * @param request
     * @return
     */
    @PostMapping("/add")
    public Result addComment(@RequestBody Blog_comment blog_comment, HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        Integer id = tokenInfo.getClaim("id").asInt();
        String username = tokenInfo.getClaim("username").asString();
        blog_comment.setCreateBy(Long.valueOf(id));
        blog_commentService.save(blog_comment);
        blog_commentMapper.addCommentNum(blog_comment.getBlogId());
        return new Result(1,"评论成功","");
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteComment(HttpServletRequest request,@PathVariable("id") Integer id) {
        UpdateWrapper<Blog_comment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).eq("rootId",id);
        blog_commentMapper.update(null,updateWrapper);
        blog_commentMapper.reduceCommentNum( blog_commentService.getById(id).getBlogId());
        return new Result(1,"删除成功","");
    }
}
